﻿Imports System.ComponentModel
Imports System.Runtime.CompilerServices
Imports System.IO.IsolatedStorage
Imports System.IO
Imports System.Reflection
Imports Xceed.Wpf.Toolkit.PropertyGrid.Editors
Imports System.Runtime.InteropServices

Public Class Settings
    Implements INotifyPropertyChanged
    Public Shadows Event PropertyChanged As PropertyChangedEventHandler Implements System.ComponentModel.INotifyPropertyChanged.PropertyChanged
    Private Sub NotifyPropertyChanged(<CallerMemberName()> Optional ByVal propertyName As String = Nothing)
        Dim handler As PropertyChangedEventHandler = Me.PropertyChangedEvent
        If handler IsNot Nothing Then
            handler.Invoke(Me, New PropertyChangedEventArgs(propertyName))
            Save()
        End If
    End Sub

    Public Const URLRequestDNS As String = "http://tunlr.net/tunapi.php?action=getdns&version=1&format=json"

    Public Sub New()

        Try
            Dim _streamReader As StreamReader
            Dim _appName As String = String.Empty

            'Get application Name
            If Windows.Application.ResourceAssembly Is Nothing Then
                _appName = String.Empty
            Else
                _appName = Windows.Application.ResourceAssembly.GetName().Name
            End If

            'Get Isolated Storage File
            Dim isolatedStorage As IsolatedStorageFile
            If AppDomain.CurrentDomain.ActivationContext Is Nothing Then
                isolatedStorage = IsolatedStorageFile.GetUserStoreForAssembly()
            Else
                isolatedStorage = IsolatedStorageFile.GetUserStoreForApplication()
            End If
            _streamReader = New StreamReader(New IsolatedStorageFileStream(If(_appName <> String.Empty, _appName & ".xml", "Settings.xml"), FileMode.Open, isolatedStorage))

            'Create XMLFile Reader
            If Not _streamReader Is Nothing Then
                Dim _xmlFile As String = _streamReader.ReadToEnd()

                For Each props As PropertyInfo In GetType(Settings).GetProperties
                    Try

                        'For each property in Class, Read it from XML Settings File, If dose not exists Leave it with default Value
                        Dim _xmlelement As XElement = (From _element In XElement.Parse(_xmlFile).<Properties>.Elements Where _element.Name = props.Name Select _element).FirstOrDefault
                        If _xmlelement Is Nothing Then Exit Try

                        'Convert Value to proprerty Type
                        Select Case props.PropertyType
                            Case GetType(TimeSpan)
                                CallByName(Me, props.Name, CallType.Set, TimeSpan.Parse(_xmlelement.Value))
                            Case Else
                                CallByName(Me, props.Name, CallType.Set, _xmlelement.Value)
                        End Select

                        'Property dose not Exists in XML File soLeave it as Default
                    Catch ex As Exception
                        Exit Try
                    End Try

                Next

                'Release XML File
                _xmlFile = String.Empty
            End If
            'Close Reader
            _streamReader.Close()


        Catch ex As Exception

        End Try
    End Sub

    Public Function Save()
        Try
            Dim srWriter As StreamWriter
            Dim _appName As String = String.Empty
            If Windows.Application.ResourceAssembly Is Nothing Then
                _appName = String.Empty
            Else
                _appName = Windows.Application.ResourceAssembly.GetName().Name
            End If

            Dim isolatedStorage As IsolatedStorageFile
            If AppDomain.CurrentDomain.ActivationContext Is Nothing Then
                isolatedStorage = IsolatedStorageFile.GetUserStoreForAssembly
            Else
                isolatedStorage = IsolatedStorageFile.GetUserStoreForApplication
            End If
            srWriter = New StreamWriter(New IsolatedStorageFileStream(If(_appName <> String.Empty, _appName & ".xml", "Settings.xml"), FileMode.Create, isolatedStorage))


            srWriter.WriteLine(String.Format("<Xml>{0}<Properties>", If(_appName <> String.Empty, String.Format("<AppName>{0}</AppName>", _appName), "")))
            For Each props As PropertyInfo In GetType(Settings).GetProperties
                Try
                    srWriter.WriteLine(String.Format("<{0}><![CDATA[{1}]]></{0}>", props.Name, CallByName(Me, props.Name, CallType.Get)))
                Catch ex As Exception
                    Exit Try
                End Try
            Next
            srWriter.WriteLine("</Properties></Xml>")

            srWriter.Flush()
            srWriter.Close()
            Return True

        Catch ex As System.Security.SecurityException
            Throw New System.Security.SecurityException("Unable to Save Settings File")
        End Try
    End Function

    Private _CheckInterval As New TimeSpan(0, 0, 30)
    <Category("Syncronization")> _
    <DisplayName("Check Interval")> _
    <Description("Sync interval with Tunlr.net")> _
    Public Property CheckInterval() As TimeSpan
        Get
            Return _CheckInterval
        End Get
        Set(ByVal value As TimeSpan)
            If value.TotalSeconds < 30 Then Exit Property
            _CheckInterval = value
            NotifyPropertyChanged()
        End Set
    End Property

    <Category("Advanced")> _
    <DisplayName("Start with Windows")> _
    <Description("Start application automatically when Windows Logon")> _
    Public Property StartWithWindows As Boolean
        Get
            Return ginkyo.AdvancedApi.WPFApplication.ApplicationProperties.StartWithWindows
        End Get
        Set(value As Boolean)
            ginkyo.AdvancedApi.WPFApplication.ApplicationProperties.StartWithWindows = value
            NotifyPropertyChanged()
        End Set
    End Property

    Private _AutoSync As Boolean = True
    <Category("Syncronization")> _
    <DisplayName("Sincronization Enable")> _
    <Description("Sincronization with Tunlr.net")> _
    Public Property AutoSync() As Boolean
        Get
            Return _AutoSync
        End Get
        Set(ByVal value As Boolean)
            _AutoSync = value
            NotifyPropertyChanged()
        End Set
    End Property

    Private _nic As String
    <Browsable(False)> _
    Public Property NIC() As String
        Get
            Return _nic
        End Get
        Set(ByVal value As String)
            _nic = value
            NotifyPropertyChanged()
        End Set
    End Property


End Class
